package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.lkd.service.impl.VendingMachineServiceImpl;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;


    /**
     * 售货机的扫描任务
     *
     * @param param
     * @return
     */
    @XxlJob("VendingMachine")
    public ReturnT<String> VendingMachine(String param) {
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //总数
        int total = shardingVo.getTotal();
        //索引
        int index = shardingVo.getIndex();
        log.info("分片参数  当前分片索引{}   总分片数{}", index, total);
        XxlJobLogger.log("分片参数  当前分片索引" + index + "  总分片数" + total);
        //1.查询所有正在运行的售货机
        QueryWrapper<VendingMachineEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING).apply("mod(id," + total + ")=" + index);
        List<VendingMachineEntity> list = vendingMachineService.list(wrapper);
        //循环扫描所有的售货机
        list.forEach(vm -> {
            XxlJobLogger.log("扫描售货机" + vm.getInnerCode());
            //售货机软编号
            vendingMachineService.sendSupplyTask(vm.getInnerCode());
        });
        //返回成功结果
        return ReturnT.SUCCESS;

    }


}
